<template>
  <el-form label-width="120px" style="margin-top: 10px;" :label-position="labelPosition">
    <el-collapse v-model="activeNames">
      <el-collapse-item title="商品基本信息" name="productBaseInfo">
        <el-form-item label="商品状态" v-if="product.id">
          <el-tag v-if="product.auditStatus === 0" type="warning" size="large">未审核</el-tag>
          <el-tag v-else :type="product.auditStatus === 1 ? 'success' : 'danger' " size="large">
            {{ product.auditStatus === 1 ? "审核通过" : "审核未通过" }}
          </el-tag>
          <el-tag v-if="product.status === 0" type="warning" size="large">未上架</el-tag>
          <el-tag v-else :type="product.status === 1 ? 'success' : 'danger' " size="large">
            {{ product.status === 1 ? "已上架" : "自主下架" }}
          </el-tag>
        </el-form-item>
        <el-form-item label="商品名称">
          <el-input
            v-model="product.name"
            maxlength="50"
            placeholder="输入商品名称"
            clearable
            style="width: 500px" />
        </el-form-item>
        <el-form-item label="分类">
          <SelectCategory :searchCategoryIdList="searchCategoryIdList" @handleChange="categoryChange"
                          style="width: 220px" />
        </el-form-item>
        <el-form-item label="品牌">
          <el-select
            class="m-2"
            placeholder="选择品牌"
            v-model="product.brandId"
            filterable
            style="width: 220px">
            <el-option
              v-for="item in categoryBrandList"
              :key="item.id"
              :label="item.brandName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="商品单元">
          <el-select
            v-model="product.unitName"
            style="width: 220px"
            class="m-2"
            placeholder="选择商品单元"
            filterable
          >
            <el-option
              v-for="item in unitList"
              :key="item.id"
              :label="item.name"
              :value="item.name"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="轮播图">
          <el-upload
            v-model:file-list="sliderList"
            :action="`${BASE_URL}/admin/product/image/upload`"
            list-type="picture-card"
            multiple
            :on-preview="() => ElMessage.warning('暂不支持图片预览')"
            :on-success="handleSliderSuccess"
            :on-remove="handleSliderRemove"
            :before-upload="beforeUpload"
            :headers="headers"
          >
            <el-icon>
              <Plus />
            </el-icon>
          </el-upload>
        </el-form-item>
      </el-collapse-item>
      <el-collapse-item title="商品SKU信息" name="skuInfo">
        <el-form-item label="选择规格">
          <el-tag
            v-if="product.id"
            effect="plain">
            <strong>{{ product.specName }}</strong>
          </el-tag>
          <el-select
            v-else
            :disabled="product.id"
            v-model="product.specValueId"
            style="width: 280px"
            class="m-2"
            placeholder="选择规格"
            size="default"
            @change="changeSpecValueList"
            filterable
          >
            <el-option
              v-for="item in specList"
              :key="item.specValue"
              :label="item.specName"
              :value="+item.id"
            />
          </el-select>
        </el-form-item>
        <div class="specValue" v-for="(item , index) in specValueList" :key="index">
          <span class="tag-group__title">{{ item.key }}：</span>
          <el-tag
            v-for="(specValue , index) in item.valueList"
            :key="index"
            effect="plain"
            class="spec_tag">
            {{ specValue }}
          </el-tag>
        </div>
        <el-form-item label="商品SKU">
          <el-table :data="product.productSkuList" border style="width: 100%">
            <el-table-column prop="skuSpec" label="规格" width="180" />
            <el-table-column label="缩略图" #default="scope" width="80">
              <UploadImage
                :image-url="scope.row.thumbImg"
                :old-files="oldFiles"
                :business-id="scope.$index"
                @uploadSuccess="handleThumbImgUploadSuccess"
                :before-upload="beforeUpload"
                imageClass="spec_thumbImg" />
            </el-table-column>
            <el-table-column label="售价" #default="scope">
              <el-input v-model.trim="scope.row.salePrice" maxlength="8" />
            </el-table-column>
            <el-table-column label="市场价" #default="scope">
              <el-input v-model.trim="scope.row.marketPrice" maxlength="8" />
            </el-table-column>
            <el-table-column label="成本价" #default="scope">
              <el-input v-model.trim="scope.row.costPrice" maxlength="8" />
            </el-table-column>
            <el-table-column label="库存数" #default="scope">
              <el-input v-model.trim="scope.row.stockNum" maxlength="10" />
            </el-table-column>
            <el-table-column label="重量" #default="scope">
              <el-input v-model.trim="scope.row.weight" maxlength="8" />
            </el-table-column>
            <el-table-column label="体积" #default="scope">
              <el-input v-model.trim="scope.row.volume" maxlength="8" />
            </el-table-column>
          </el-table>
        </el-form-item>
      </el-collapse-item>
      <el-collapse-item title="商品详情信息" name="productDetails">
        <el-form-item label="商品描述">
          <el-input
            type="textarea"
            :autosize="{ minRows: 2, maxRows: 4}"
            placeholder="输入商品描述"
            maxlength="500"
            v-model.trim="product.productDetails.productDesc">
          </el-input>
        </el-form-item>
        <el-form-item label="详情图片">
          <el-upload
            v-model:file-list="detailsFileList"
            :action="`${BASE_URL}/admin/product/image/upload`"
            list-type="picture-card"
            multiple
            :on-preview="() => ElMessage.warning('暂不支持图片预览')"
            :on-success="handleDetailsSuccess"
            :on-remove="handleDetailsRemove"
            :before-upload="beforeUpload"
            :headers="headers"
          >
            <el-icon>
              <Plus />
            </el-icon>
          </el-upload>
        </el-form-item>
      </el-collapse-item>
      <el-collapse-item title="提交数据" name="submit" :disabled="true">
        <el-form-item>
          <el-button type="primary" @click="submit">提交</el-button>
          <el-button @click="closeForm">取消</el-button>
        </el-form-item>
      </el-collapse-item>
    </el-collapse>
  </el-form>
</template>

<script setup>
import { onMounted, ref, watch, nextTick } from "vue";
import { FindAllProductUnit } from "@/api/product/productunit";
import { FindAllProductSpec } from "@/api/product/productSpec.js";
import { getBrandByCategoryId } from "@/api/product/categoryBrand.js";
import { deepClone } from "@/utils";
import SelectCategory from "@/components/SelectCategory/selectCategory.vue";
import UploadImage from "@/components/UploadImage/uploadImage.vue";
import FileApi from "@/api/product/file";
import ProductApi from '@/api/product/product'
import { BASE_URL } from "@/utils/request";
import { useApp } from "@/pinia/modules/app";
import { ElMessage } from "element-plus";

const headers = {
  token: useApp().authorization.token     // 从pinia中获取token，在进行文件上传的时候将token设置到请求头中
};
// 表单数据
const props = defineProps({
  defaultForm: {
    type: Object
  },
  dialogVisible: {
    type: Boolean,
    default: false
  },
  productId: {
    type: undefined
  }
});
const product = ref(deepClone(props.defaultForm));  // 表单渲染数据
// 传给子组件选择好的分类ID
const searchCategoryIdList = ref([]);

// 激活面版
const activeNames = ref(["productBaseInfo", "skuInfo", "productDetails", "submit"]);

const emits = defineEmits(["submitForm", "closeForm"]);

onMounted(() => {
  fetchProductUnit();
  fetchProductSpec();
});

// 监听父组件表单显示
watch(() => props.dialogVisible, newValue => {
  // 判断表单弹窗状态
  if (newValue) {
    // 判断是否有商品ID，如果有则为修改
    if (props.productId) nextTick(() => getById(props.productId));
  }
  // 关闭表单弹窗
  else {
    nextTick(() => {
      // 删除之前上传的冗余图片
      if (oldFiles.value.length) FileApi.remove(oldFiles.value);
      // 清空表单数据和图片缓存
      product.value = deepClone(props.defaultForm);
      searchCategoryIdList.value = []
      specValueList.value = [];
      oldFiles.value = [];
      saveFiles.value = [];
      sliderList.value = []
      sliderUrlList.value = []
      detailsFileList.value = []
      detailsImageUrlList.value = []
    });
  }
}, { immediate: true });

// 根据ID获取商品信息，并处理成表单
const getById = async id => {
  const { data } = await ProductApi.getProductInfoById(id);
  product.value = data;
  // 处理个别字段映射问题
  product.value.name = data.productName;
  product.value.specValue = data.specValue;
  //分类赋值
  searchCategoryIdList.value = [+product.value.category1Id, +product.value.category2Id, +product.value.category3Id];
  getBrand(product.value.category3Id)

  //处理轮播图
  sliderList.value = [];
  sliderUrlList.value = product.value.productDetails.sliderUrls.split(",");
  sliderUrlList.value.forEach(url => sliderList.value.push({ url }));

  //处理详情图片
  detailsFileList.value = [];
  detailsImageUrlList.value = product.value.productDetails.imageUrls.split(",");
  detailsImageUrlList.value.forEach(url => detailsFileList.value.push({ url }));
};

// 分类级联选择器数据发送改变以后的事件处理函数
const categoryChange = (lastId, ids) => {
  product.value.categories = ids;
  if (lastId) getBrand(lastId);
};

// 定义品牌的数据模型
const categoryBrandList = ref([]);
// 从数据库获取品牌数据
const getBrand = async id => {
  const { data } = await getBrandByCategoryId(id);
  categoryBrandList.value = data;
};
// 商品单元的数据模型
const unitList = ref([]);
// 查询所有的商品单元
const fetchProductUnit = async () => {
  const { data } = await FindAllProductUnit();
  unitList.value = data;
};
// 商品规格数据数据模型
const specList = ref([]);
// 查询产品规格数据
const fetchProductSpec = async () => {
  const { data } = await FindAllProductSpec();
  specList.value = data;
};
// 展示选择的规则数据
const specValueList = ref([]);
const changeSpecValueList = () => {
  if (!product.value.specValueId) return;
  const targetSpec = specList.value.find(item => +item.id === product.value.specValueId);
  specValueList.value = JSON.parse(targetSpec.specValue);
  // 获取 valueList 集合
  const specValueArr = [];
  specValueList.value.forEach(item => {
    specValueArr.push(item.valueList);
  });
  // last为上次运算的结果，current为数组中的当前元素
  const specValueGroup = specValueArr.reduce((last, current) => {
    const group = [];
    last.forEach(par1 => {
      // 列：8G + 256G
      current.forEach(par2 => group.push(par1 + " + " + par2));
    });
    return group;
  });
  product.value.productSkuList = [];
  specValueGroup.forEach(item => product.value.productSkuList.push({ skuSpec: item }));
};

// --------------------------- 上传操作 --------------------------------
// 缓存已上传的图片
const oldFiles = ref([]);
// 真正保存的图片
const saveFiles = ref([]);
// 商品规格缩略图 上传成功的勾子
const handleThumbImgUploadSuccess = (imgSrc, index) => {
  oldFiles.value.push(imgSrc);
  product.value.productSkuList[index].thumbImg = imgSrc;
};

// 上传商品轮播图图片
const sliderList = ref([]);
const sliderUrlList = ref([]);
const handleSliderSuccess = response => {
  sliderUrlList.value.push(response.data);
};
const handleSliderRemove = uploadFile => {
  if (!uploadFile.response) return;
  const filepath = uploadFile.response.data;
  sliderUrlList.value.splice(sliderUrlList.value.indexOf(filepath), 1);
  FileApi.remove([filepath]);
};

// 上传商品详情图片
const detailsFileList = ref([]);
const detailsImageUrlList = ref([]);
const handleDetailsSuccess = response => {
  detailsImageUrlList.value.push(response.data);
};
const handleDetailsRemove = uploadFile => {
  if (!uploadFile.response) return;
  const filepath = uploadFile.response.data;
  detailsImageUrlList.value.splice(detailsImageUrlList.value.indexOf(filepath), 1);
  FileApi.remove([filepath]);
};

// 上传前图片校验
const beforeUpload = (rawFile) => {
  const suffix = rawFile.name.substring(rawFile.name.lastIndexOf(".") + 1);
  const reg = /^(gif|jpg|jpeg|png)$/;
  if (!reg.test(suffix)) {
    ElMessage.warning("图片格式不支持，支持的格式：png/jpg/jpeg/gif");
    return false;
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error("图片大小不能超过 2MB！");
    return false;
  }
  return true;
};

// ----------------- 提交 -----------------
// 提交表单
const submit = () => {

  // 修改，得到要删除的旧图片
  const diffListBySliderAndImageUrl = []
  if (product.value.id) {
    console.log(product.value.productDetails.sliderUrls.split(','));
    console.log(product.value.productDetails.imageUrls.split(','));
    // 数组求差集

  }

  // 处理轮播图，详情图，转换格式 [1,2] -> 1,2
  product.value.productDetails.sliderUrls = sliderUrlList.value.join(',')
  product.value.productDetails.imageUrls = detailsImageUrlList.value.join(',')

  emits("submitForm", product.value);

  // 遍历表单规格数据，获取规格缩略图列表，再与上传的冗余图片列表做差集，最后删除差集里的图片
  saveFiles.value = product.value.productSkuList.map(item => item.thumbImg);
  // 得到两个数组的差集
  const diffListByThumbImg = oldFiles.value.filter(item => !saveFiles.value.includes(item));

  FileApi.remove([...diffListByThumbImg, ...diffListBySliderAndImageUrl]);
  // 清空图片缓存
  oldFiles.value = [];
  saveFiles.value = [];
};

// 关闭表单
const closeForm = () => {
  emits("closeForm");
};
</script>

<style scoped>
:deep(.el-collapse-item__header) {
  font-size: 14px;
  font-weight: bold;
}

:deep(.el-tag) {
  margin-right: 5px;
}

.product_image {
  width: 120px;
  height: 120px;
  margin-right: 10px;
}

.tag-group__title {
  margin-right: 10px; /* 调整元素之间的水平间距 */
}

.specValue {
  margin: 10px 0 10px 120px;
}

.spec_tag {
  margin: 3px;
}

:deep(.spec_thumbImg) {
  font-size: 18px;
  width: 50px;
  height: 50px;
}
</style>
